package com.wmx.thread.synchronize_and_lock;

import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**********************************
 * @author wmx
 * @date 2019/8/20 17:05
 * @description:
 * @version 1.0
 ************************************/
public class LockTest {
    private static ArrayList<Integer> integerArrayList = new ArrayList<>();
    Lock lock = new ReentrantLock();
    public static void main(String[] args) {
       final LockTest lockTest = new LockTest();
       Thread thread =  new Thread(()->{
           lockTest.insert(Thread.currentThread());
       });
       Thread thread1 = new Thread(()->{
            lockTest.insert(Thread.currentThread());
        });

       thread.start();
       thread1.start();
        try {
            thread.join();
            thread1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        integerArrayList.forEach(tem->{
           System.out.println(tem);
       });
    }

    private void insert(Thread thread){
     /*   线程Thread-0获得锁
        线程Thread-1获得锁
        线程Thread-0释放锁
        线程Thread-1释放锁
      */
      //  Lock lock = new ReentrantLock(); // 注意
        lock.lock();
        try {
            System.out.println("线程"+thread.getName()+"获得锁");
            for (int i = 0 ;i<5;i++){
                integerArrayList.add(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println("线程"+thread.getName()+"释放锁");
        }


    }
}
